//
//  MCActionDetailVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/5/17.
//

import UIKit
import SnapKit
import Toast_Swift
import QMUIKit
import ObjectMapper
import JKSwiftExtension
import SwiftyJSON
import Kingfisher
import CLPlayer
import CustomPopOverView

//动作详情页
class MCActionDetailVc: MCBaseVc,CustomPopOverViewDelegate {
    
    //tableView
    let actionDetailTableViewIdentifier = "actionDetailTableViewIdentifier"
    
    //多视图
    let multuiCollectionViewIdentifier = "multuiCollectionViewIdentifier"
    
    
    //器械
    let actionMainchieyIdentifier = "actionMainchieyIdentifier"
    
    //注意看点
    let actionKeyPointIdentifier = "actionKeyPointIdentifier"
    
    
    
    
    public var ids:String = ""
    
    
    //多视图
    var manyViewColView:UICollectionView!
    
    //对称视图
    var symmetryCollectionView:UICollectionView?
    
    
    
    //锻炼肌肉
    var mainMuscleCollectionView:UICollectionView?
    
    //器械
    var machineryColView:UICollectionView!
    private var instrumentsDataSource:Array = [MCActionDetailSecondInstrumentList?]()
    
    
    //重点
    var keynoteColView:UICollectionView!
    
    private var keyNoteDataSource:Array = [MCActionDetailSecondActionAttentionList?]()
   
    var headerView:MCActionHeaderView!
        
    
    @IBOutlet weak var actionTableView: UITableView!
    
    private var multiDataSource:Array<MCMultiViewDisPlayModel> = [MCMultiViewDisPlayModel]()
    
    private var tableDataSource:Array<MCActionListActionTypeList?> = [MCActionListActionTypeList?]()
    
    private var allActionList:Array<MCActionDetailSecondActionDetailList?> = [MCActionDetailSecondActionDetailList?]()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        
        actionTableView.dataSource = self
        actionTableView.delegate = self
        
        self.actionTableView.register(UINib(nibName: "MCActionTableCell", bundle: Bundle.main), forCellReuseIdentifier: actionDetailTableViewIdentifier)
        
        loadWithSubViews()
    }
    
    func loadWithSubViews() -> Void {
      
        
        let mcheaderView = MCActionHeaderView.initActionHeaderView()
        self.headerView = mcheaderView
        self.actionTableView.tableHeaderView = mcheaderView
        
        //器械
        let machineryFlowLayout = UICollectionViewFlowLayout.init()
        machineryFlowLayout.scrollDirection = .horizontal
        mcheaderView.instrumentCollectionView.setCollectionViewLayout(machineryFlowLayout, animated: true)
        mcheaderView.instrumentCollectionView.dataSource = self
        mcheaderView.instrumentCollectionView.delegate = self
        mcheaderView.instrumentCollectionView.register(UINib(nibName: "MCTrainInterumentCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: actionMainchieyIdentifier)
        self.machineryColView = mcheaderView.instrumentCollectionView
        
        //注意重点
        let keyNoteFlowLayout = UICollectionViewFlowLayout.init()
        keyNoteFlowLayout.scrollDirection = .horizontal
        headerView.keynoteCollectionView.setCollectionViewLayout(keyNoteFlowLayout, animated: true)
        headerView.keynoteCollectionView.dataSource = self
        headerView.keynoteCollectionView.delegate = self
        headerView.keynoteCollectionView.register(UINib(nibName: "MCActionKeyNoteCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: actionKeyPointIdentifier)
        self.keynoteColView = headerView.keynoteCollectionView
        
        
        let multiViewFlowLayout = UICollectionViewFlowLayout.init()
        multiViewFlowLayout.scrollDirection = .vertical
        multiViewFlowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        multiViewFlowLayout.minimumLineSpacing = 0
        multiViewFlowLayout.minimumInteritemSpacing = 0
        headerView.mulutiViewCollectionView.setCollectionViewLayout(multiViewFlowLayout, animated: true)
        headerView.mulutiViewCollectionView.dataSource = self
        headerView.mulutiViewCollectionView.delegate = self
        headerView.mulutiViewCollectionView.isScrollEnabled = false
        headerView.mulutiViewCollectionView.register(UINib(nibName: "MCActionDetailVideoCollectionCell", bundle: Bundle.main), forCellWithReuseIdentifier: multuiCollectionViewIdentifier)
        
        
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.qmui_item(withTitle: "切换演示模特", target: self, action: #selector(rightTitleData))
        
        //详情页
        getDetailData()
    }
    
    
    //右边点击切换
    @objc func rightTitleData() -> Void {
        
        let meunsArr = ["虚拟(男)","虚拟(女)","真人(男)","真人(女)"]
        
        let showStyle = CPShowStyle.init()
        
        showStyle.roundMargin = 5
        showStyle.triAngelWidth = 0.0
        showStyle.triAngelHeight = 0.0
        showStyle.containerCornerRadius = 5.0
        showStyle.roundMargin = 10.0
        showStyle.showSpace = 5.0
        showStyle.containerBackgroudColor = UIColor.white
        showStyle.containerBorderColor = UIColor.qmui_color(withHexString: "#333333")
        showStyle.containerBorderWidth = 2.0
        
        let pView = CustomPopOverView.init(bounds: CGRect(x: 0, y: 0, width:120, height: 300), titleMenus: meunsArr, style: showStyle)
        pView?.delegate = self
        pView?.show(from:nil, alignStyle: CPAlignStyle.right,relativePosition: .alwaysDown)
        
    }
    
    func popOverView(_ pView: CustomPopOverView!, didClickMenuIndex index: Int) {
        
    }
    
    func getDetailData() -> Void
    {
        NetWorkRequest(MCActionDetailApi.getActionDetail(ids: self.ids)) { ResponseModel in
            let actionSecondRecommandFemaleModel  = MCActionDetailSecondrecommandfemaleModel.init(JSONString: ResponseModel.dataString)
            
            //中/英--文
            self.headerView.titleEnLabel.text = actionSecondRecommandFemaleModel?.enName ?? ""
            self.headerView.titleZhNameLabel.text = actionSecondRecommandFemaleModel?.zhName ?? ""
            
            //益处
            self.headerView.yiChuLabel.text = actionSecondRecommandFemaleModel?.benefit ?? ""
            //锻炼部位
            self.headerView.mainPostionLabel.text = actionSecondRecommandFemaleModel?.exercisePosition ?? ""
            //锻炼肌肉
            self.headerView.mainMusleLabel.text = actionSecondRecommandFemaleModel?.exerciseMuscle ?? ""
            //动作步骤
            self.headerView.acionStepLabel.text = actionSecondRecommandFemaleModel?.actionStep ?? ""
            //呼吸方式
            self.headerView.breatheLabel.text = actionSecondRecommandFemaleModel?.breatheType ?? ""
            //锻炼频率
            self.headerView.frequencyLabel.text = actionSecondRecommandFemaleModel?.exerciseRate ?? ""
            
            
            if actionSecondRecommandFemaleModel?.actionAttentionList?.isEmpty == false {
                self.keyNoteDataSource.append(contentsOf: actionSecondRecommandFemaleModel?.actionAttentionList ?? [])
                
                self.keynoteColView.reloadData()
            }
            
            if actionSecondRecommandFemaleModel?.instrumentList?.isEmpty == false {
                self.instrumentsDataSource.append(contentsOf: actionSecondRecommandFemaleModel?.instrumentList ?? [])
                self.machineryColView.reloadData()
            }
            
            self.tableDataSource.append(contentsOf: actionSecondRecommandFemaleModel?.actionList ?? [])
            
            self.actionTableView.reloadData()
            
            if actionSecondRecommandFemaleModel?.actionType == 0 {
                self.headerView.expansionActionsLabel.text = "基础动作"
            }else if actionSecondRecommandFemaleModel?.actionType == 1 {
                self.headerView.expansionActionsLabel.text = "拓展动作"
            }else {
                self.headerView.expansionActionsLabel.text = ""
            }
            
            if actionSecondRecommandFemaleModel?.actionDetailList?.isEmpty == false {
                
                self.allActionList.append(contentsOf: actionSecondRecommandFemaleModel?.actionDetailList ?? [])
                
                let actionDetailModel = actionSecondRecommandFemaleModel?.actionDetailList?.first
                
                
                //立体图
                if actionDetailModel?.stereogramUrl != nil  {
                    if actionDetailModel?.stereogramUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.stereogramUrl
                        muletDisPlayModel?.title = "立体图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                        
                    }
                    
                }
                
                //左视图
                if actionDetailModel?.leftUrl != nil  {
                    if actionDetailModel?.leftUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.leftUrl
                        muletDisPlayModel?.title = "左视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //右视图
                if actionDetailModel?.rightUrl != nil  {
                    if actionDetailModel?.rightUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.rightUrl
                        muletDisPlayModel?.title = "右视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //主视图
                if actionDetailModel?.frontUrl != nil  {
                    if actionDetailModel?.frontUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.frontUrl
                        muletDisPlayModel?.title = "正视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
               //后视图
                if actionDetailModel?.backUrl != nil  {
                    if actionDetailModel?.backUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.backUrl
                        muletDisPlayModel?.title = "后视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //俯视图
                if actionDetailModel?.verticalUrl != nil  {
                    if actionDetailModel?.verticalUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.verticalUrl
                        muletDisPlayModel?.title = "俯视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //仰视图
                if actionDetailModel?.bottomUrl != nil  {
                    if actionDetailModel?.bottomUrl?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.bottomUrl
                        muletDisPlayModel?.title = "仰视图"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //其他视图1
                if actionDetailModel?.otherUrl1 != nil  {
                    if actionDetailModel?.otherUrl1?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.otherUrl1
                        muletDisPlayModel?.title = "其他视图1"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                //其他视图2
                if actionDetailModel?.otherUrl2 != nil  {
                    if actionDetailModel?.otherUrl2?.isEmpty == false {
                        let muletDisPlayModel = MCMultiViewDisPlayModel(JSON: [:])
                        muletDisPlayModel?.videoUrl = actionDetailModel?.otherUrl2
                        muletDisPlayModel?.title = "其他视图2"
                        
                        self.multiDataSource.append(muletDisPlayModel!)
                    }
                    
                }
                
                //对称视图
                self.headerView.symmetricViewImageView.kf.setImage(with:URL(string:actionDetailModel?.symmetryUrl ?? ""))
                
                //肌肉123
                self.headerView.muscleHeaderImage1.kf.setImage(with:URL(string:actionDetailModel?.muscleUrl1 ?? ""))
                self.headerView.muscleHeaderImage2.kf.setImage(with:URL(string:actionDetailModel?.muscleUrl2 ?? ""))
                self.headerView.muscleHeaderImage3.kf.setImage(with:URL(string:actionDetailModel?.muscleUrl3 ?? ""))
                
                self.headerView.mulutiViewCollectionView.reloadData()
                
                if self.multiDataSource.count % 3 == 0 {
                    print(self.multiDataSource.count)
                    print(self.headerView.muletViewCollectionLayout.constant)
                  
                    self.headerView.muletViewCollectionLayout.constant = 300
                    print(self.headerView.muletViewCollectionLayout.constant)
                    self.headerView.layoutIfNeeded()
                }else{
                 
                }
                 
                
            }
            
            
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    


}

extension MCActionDetailVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
   
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if self.headerView.mulutiViewCollectionView == collectionView {
            return CGSize(width: (ScreenWidth - 1) / 3.0, height: 70)
        }else {
            return CGSize(width: 200, height: 70)
        }
       
    }
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if collectionView == self.headerView.keynoteCollectionView {
            return self.keyNoteDataSource.count
        }else if collectionView == self.headerView.instrumentCollectionView {
            return self.instrumentsDataSource.count
        }else if collectionView == self.headerView.mulutiViewCollectionView {
            return self.multiDataSource.count
        } else {
            return 10
        }
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
       if collectionView == self.headerView.instrumentCollectionView  {
            let cell:MCTrainInterumentCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: actionMainchieyIdentifier, for: indexPath) as! MCTrainInterumentCollectionCell
            let instrumentsList = self.instrumentsDataSource[indexPath.row]
            cell.headerImageVIew.kf.setImage(with: URL(string: instrumentsList?.previewPic ?? ""))
            cell.titleInfoActionLabel.text = instrumentsList?.zhName ?? ""
            return cell
       }else if collectionView == self.headerView.mulutiViewCollectionView {
           let cell:MCActionDetailVideoCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: multuiCollectionViewIdentifier, for: indexPath) as! MCActionDetailVideoCollectionCell
           
           for viderViewSubViews in cell.viderView.subviews {
               viderViewSubViews.removeFromSuperview()
           }
           
           let multiViewModel = self.multiDataSource[indexPath.row]
           
         
           cell.titleStr = multiViewModel.title ?? ""
           cell.viderUrlStr = multiViewModel.videoUrl ?? ""
           cell.backgroundColor = UIColor.qmui_random()
 
           return cell
       } else{
            let cell:MCActionKeyNoteCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: actionKeyPointIdentifier, for: indexPath) as! MCActionKeyNoteCollectionCell
            let keyNoteModel = self.keyNoteDataSource[indexPath.row]
            cell.headerImageView.kf.setImage(with: URL(string: keyNoteModel?.attentionUrl ?? ""))
            cell.titleInfoLabel.text = keyNoteModel?.attentionName ?? ""
            cell.subTitleLabel.text = keyNoteModel?.attentionDescription ?? ""
            return cell
        }
        
    }
    
}

extension MCActionDetailVc:UITableViewDelegate,UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.tableDataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 75
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCActionTableCell = tableView.dequeueReusableCell(withIdentifier: actionDetailTableViewIdentifier, for: indexPath) as! MCActionTableCell
        let tableInfoModel = self.tableDataSource[indexPath.row]
        
        cell.headerImageView.kf.setImage(with: URL(string: tableInfoModel?.previewUrl ?? ""))
        cell.titleInfoLabel.text = tableInfoModel?.zhName ?? ""
        cell.subTitleInfoLabel.text = tableInfoModel?.actionLabel ?? ""
        return cell
    }
    
    
}
